import { AudioListener, Audio, PositionalAudio, AudioLoader } from '../libs/three137/three.module.js';
import { urls } from '../assets/store.js';

class SFX{
    constructor(camera, assetsPath){
        let constrants = { 
            audio:true ,
            // video:{width: 1080, height:720}
        }
        if(window.location.protocol === 'https' || location.hostname === 'localhost' || location.hostname === '127.0.0.1'){

            navigator.mediaDevices.getUserMedia(constrants).then((stream)=> { 
                
            })
        }
            this.listener = new AudioListener() ;
            camera.add(this.listener) ;
            this.sounds = { }
    
    }
   // 原生是  AudioContext  Audio继承自Objct3D，内部使用AudioConntext, position Audio继承自Audio
// audio内部要先调用play 才有source ,stop需要source
    load(name, loop=false, vol=0.5, obj=null){
        const sound  = !obj? new Audio(this.listener):new PositionalAudio(this.listener) ;
        
        const audioLoader = new AudioLoader() ;
        audioLoader.load(urls[`${name}_mp3`], buffer => {
            sound.setBuffer(buffer) ;
            sound.setLoop(loop) ;
            sound.setVolume(vol) ;
            this.sounds[name]= sound ;
            console.log(sound);
            sound.play(1) 
            sound.stop()
       })   
    }

    setVolume(name, volume){
        let sound = this.sounds[name] ;
        if(sound){ sound.setVolume(volume) }
        
    }

    setLoop(name, loop){
        
        let sound = this.sounds[name] ;
        if(sound){ sound.setLoop(loop) }
    }

    play(name){
        
        let sound = this.sounds[name] ;
        if(sound){ sound.play() }
    }

    stop(name){

        let sound = this.sounds[name] ;
        if(sound){ sound.stop() }        
    }

    stopAll(){
        for( let key of Reflect.ownKeys(this.sounds)){ 
            this.sounds[key]?.stop()
        }
    }

    pause(name){
        
        let sound = this.sounds[name] ;
        if(sound){ sound.pause( ) }
    }
}

export { SFX };